package com.milkshopbackend.milkshop.controller;

import com.milkshopbackend.milkshop.Service.ProductImageService;
import com.milkshopbackend.milkshop.common.Result;
import com.milkshopbackend.milkshop.entity.ProductImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/api/product/images")
public class ProductImageController {

    @Autowired
    private ProductImageService productImageService;

    @PostMapping("/upload")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String imageUrl = productImageService.uploadImage(file);
            return Result.success(imageUrl);
        } catch (Exception e) {
            return Result.error(500, "上传图片失败：" + e.getMessage());
        }
    }

    @PostMapping
    public Result<Void> addProductImage(
            @RequestParam("productId") Long productId,
            @RequestParam("imageUrl") String imageUrl,
            @RequestParam("imageType") Integer imageType,
            @RequestParam(value = "sort", defaultValue = "0") Integer sort) {
        try {
            productImageService.addProductImage(productId, imageUrl, imageType, sort);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "添加商品图片失败：" + e.getMessage());
        }
    }

    @GetMapping("/{productId}")
    public Result<List<ProductImage>> getProductImages(@PathVariable Long productId) {
        try {
            List<ProductImage> images = productImageService.getProductImages(productId);
            return Result.success(images);
        } catch (Exception e) {
            return Result.error(500, "获取商品图片失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/{imageId}")
    public Result<Void> deleteProductImage(@PathVariable Long imageId) {
        try {
            productImageService.deleteProductImage(imageId);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "删除商品图片失败：" + e.getMessage());
        }
    }
} 